import urlparse
import os.path
import urllib
import re

from subprocess import Popen, PIPE

class downloader:
	
	def __init__(self):
		self.good_files = []
		self.destination = None
		
	def is_good_file(self, file_name):
		root, ext = os.path.splitext(file_name)
		return ext.lower() not in ['gif','jpg','zip','jpeg']

	def download(self, url, destination=None):
		if destination is not None:
			self.destination = destination
		
		fl = os.path.split(urlparse.urlparse(url)[2])[1]
		if not self.is_good_file(fl):
			return ""
		
		if not os.path.exists(self.destination):
			os.mkdir(self.destination)


		#fo = os.path.join(dp,fl)
		args = ["wget",
			"-nv",
			"--no-clobber", 
			"--directory-prefix", self.destination,
			"--restrict-file-names", "unix",
			url] 
		
		p = Popen(args, stdout=PIPE, stderr=PIPE)
		output = p.stdout.read()
		err = p.stderr.read()
		#wget's non verbose output gets sent to stderr
		dfn = self.get_download_filename(err)
		return dfn

	def get_download_filename(self, output):
		rs = ""
		wre = re.compile('".+"')
		mo = wre.search(output)
		if mo is not None:
			rs = mo.group()		
		return rs
